package org.anderground.editor.gui.properties.tunnel;

import java.awt.Component;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.AbstractCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;

import org.anderground.core.model.Line;
import org.anderground.core.model.Tunnel;
import org.anderground.editor.edits.EditsManager;
import org.anderground.editor.edits.SetTunnelLineAction;
import org.anderground.editor.gui.properties.AbstractPropertiesPanel;
import org.anderground.editor.gui.properties.ColorPanel;
import org.anderground.editor.model.EditorModel;

public class TunnelLineProperty implements AbstractPropertiesPanel.Property {

	@Override
	public TableCellEditor getCellEditor() {
		@SuppressWarnings("serial")
		class Editor extends AbstractCellEditor implements TableCellEditor {

			@Override
			public Component getTableCellEditorComponent(JTable table,
					Object value, boolean isSelected, int row, int column) {
				final JComboBox box = new JComboBox();
				final Tunnel tunnel = (Tunnel) value;
				for (Line line : EditorModel.getInstance().getData().getLines()) {
					box.addItem(line);
				}
				box.addItem("New...");
				box.addItemListener(new ItemListener() {

					@Override
					public void itemStateChanged(ItemEvent e) {
						if (e.getStateChange() == ItemEvent.SELECTED) {
							Line line;
							if (e.getItem() instanceof Line) {
								line = (Line) e.getItem();
							} else {
								line = new Line();
							}
							EditsManager.getInstance().performAction(
									new SetTunnelLineAction(tunnel, line));

							Editor.this.cancelCellEditing();
						}

					}

				});
				return box;
			}

			@Override
			public Object getCellEditorValue() {
				return null;
			}

		}
		return new Editor();
	}

	@Override
	public TableCellRenderer getCellRender() {
		class Render implements TableCellRenderer {

			@Override
			public Component getTableCellRendererComponent(JTable arg0,
					Object arg1, boolean arg2, boolean arg3, int arg4, int arg5) {

				Line line = ((Tunnel) arg1).getLine();

				return new ColorPanel(line.getColor(), line.getName());
			}

		}
		return new Render();
	}

	@Override
	public String getPropertyName() {
		return "Line";
	}

	@Override
	public boolean isEditable() {
		return true;
	}

}
